import javax.swing.tree.TreeNode;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LIUYANJIAO
 * Date: 2024-10-24
 * Time: 9:35
 */
public class Main {
      public static class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
  }
    public  static int i=1;
      public static int findroot(int[] inorder,int key){
          for (int j = 0; j < inorder.length; j++) {
              if(inorder[j]==key) return j;
          }
          return -1;
      }
    public static TreeNode buildChlid(int left,int right,int[] inorder, int[] postorder) {

          if(left>right) return null;
          if(i>inorder.length) return null;
          TreeNode root=new TreeNode(postorder[postorder.length-i]);
          i++;

          int center=findroot(inorder,root.val);

           root.right=buildChlid(center+1,right,inorder,postorder);
           root.left=buildChlid(left,center-1,inorder,postorder);

        return root;
    }
    public static TreeNode buildTree(int[] inorder, int[] postorder) {
        int left=0;
        int right=inorder.length-1;
        TreeNode root=buildChlid(left,right,inorder,postorder);
        return root;
    }

    public static void main(String[] args) {
        int[]arr1={9,3,15,20,7};
        int[]arr2={9,15,7,20,3};
        TreeNode root=buildTree(arr1,arr2);
        System.out.println(preorderTraversal(root));
    }
    public static List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list=new ArrayList<>();
        Stack<TreeNode> stack=new Stack<>();
        while(root!=null||!stack.isEmpty()){
            while(root!=null){
                stack.add(root);
                list.add(root.val);
                root=root.left;
            }
            root=stack.pop();
            root=root.right;
        }
        return list;
    }

    public static List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list=new ArrayList<>();
        Stack<TreeNode> stack=new Stack<>();
        while(root!=null||!stack.isEmpty()){
            while(root!=null){
                stack.add(root);
                root=root.left;
            }
            root=stack.pop();
            list.add(root.val);
            root=root.right;
        }
        return list;
    }
    public static void main1(String[] args) {
        TreeNode a=new TreeNode(1);
        TreeNode b=new TreeNode(2);
        TreeNode c=new TreeNode(3);
        a.right=b;
        b.left=c;
        System.out.println(preorderTraversal(a));;
    }
}